package com.seuic.hnapps.project;

import android.annotation.SuppressLint;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.CardView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectChangeListener;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.identity.Shell;
import com.identity.globalEnum;
import com.orhanobut.logger.Logger;
import com.seuic.hnapps.BaseActivity;
import com.seuic.hnapps.R;
import com.seuic.hnapps.SquareLayout;
import com.seuic.hnapps.bean.CardBinInfo_bean;
import com.seuic.hnapps.bean.Summary_Bean;
import com.seuic.hnapps.constants.EmvConstants;
import com.seuic.hnapps.posdsdk.pos_func.PosCallbacks;
import com.seuic.hnapps.posdsdk.pos_func.PosFuncs;
import com.seuic.hnapps.util.CZInterface;
import com.seuic.hnapps.util.CommAdapter;
import com.seuic.hnapps.util.Constants;
import com.seuic.hnapps.util.DateUtil;
import com.seuic.hnapps.util.PWDInterface;
import com.seuic.hnapps.util.PinPad;
import com.seuic.hnapps.util.PzGetUtils;
import com.seuic.hnapps.util.RTLOInterface;
import com.seuic.hnapps.util.SFInterface;
import com.seuic.hnapps.util.SFTPUtils;
import com.seuic.hnapps.util.ServiceCommon;
import com.seuic.hnapps.util.SpUtils;
import com.seuic.hnapps.util.TPUInstall;
import com.seuic.hnapps.util.Up_RundataUtils;
import com.seuic.hnapps.util.Utils;
import com.seuic.hnapps.util.VTAInterface;
import com.solab.enc.DES3;
import com.solab.enc.HexT;
import com.solab.enc.SMS4;
import com.solab.iso8583.IsoMessage;
import com.solab.iso8583.MessageFactory;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * isjingkai
 * 2019年7月20日10:39:52
 * 特殊业务
 */
public class SpecialServiceActivity extends BaseActivity {

    boolean bStop = false;

    Runnable runnable;


    String infoType = "";

    @BindView(R.id.base_back_btn)
    LinearLayout baseBackBtn;
    @BindView(R.id.base_title_text)
    TextView baseTitleText;
    @BindView(R.id.special_service_changepassword)
    SquareLayout specialServiceChangepassword;
    @BindView(R.id.special_service_report)
    SquareLayout specialServiceReport;
    @BindView(R.id.special_service_reversal)
    SquareLayout specialServiceReversal;
    @BindView(R.id.special_service_homelayout)
    LinearLayout specialServiceHomelayout;
    @BindView(R.id.special_service_vunlock)
    SquareLayout specialServiceVunlock;
    @BindView(R.id.special_service_verify)
    SquareLayout specialServiceVerify;
    @BindView(R.id.special_service_applyfor)
    SquareLayout specialServiceApplyfor;
    @BindView(R.id.verification_identity_noBtn)
    Button verificationIdentityNoBtn;
    @BindView(R.id.verification_identity_okBtn)
    Button verificationIdentityOkBtn;
    @BindView(R.id.verification_identity_layout)
    LinearLayout verificationIdentityLayout;
    @BindView(R.id.ficationing_layout)
    LinearLayout ficationingLayout;
    @BindView(R.id.dealing_layout)
    LinearLayout dealingLayout;
    @BindView(R.id.modification_success_layout)
    LinearLayout modificationSuccessLayout;
    @BindView(R.id.modification_success_okbtn)
    Button modificationSuccessOkbtn;
    @BindView(R.id.input_lossof_edtext)
    EditText inputLossofEdtext;
    @BindView(R.id.input_lossof_gzBtn)
    Button inputLossofGzBtn;
    @BindView(R.id.input_lossof_okbtn)
    Button inputLossofOkbtn;
    @BindView(R.id.input_lossof_layout)
    LinearLayout inputLossofLayout;
    @BindView(R.id.bank_name)
    TextView bankName;
    @BindView(R.id.select_certificcate_btn)
    LinearLayout selectCertificcateBtn;
    @BindView(R.id.select_certificcate_okbtn)
    Button selectCertificcateOkbtn;
    @BindView(R.id.select_certificcate_layout)
    LinearLayout selectCertificcateLayout;
    @BindView(R.id.input_certificcate_edtext)
    EditText inputCertificcateEdtext;
    @BindView(R.id.input_certificcate_nobtn)
    Button inputCertificcateNobtn;
    @BindView(R.id.input_certificcate_okbtn)
    Button inputCertificcateOkbtn;
    @BindView(R.id.input_certificcate_layout)
    LinearLayout inputCertificcateLayout;
    @BindView(R.id.modification_success_text)
    TextView modificationSuccessText;
    //    @BindView(R.id.please_input_iccard_okbtn)
//    Button pleaseInputIccardOkbtn;
    @BindView(R.id.please_input_iccard_layout)
    LinearLayout pleaseInputIccardLayout;
    @BindView(R.id.brushthe_identity_layout)
    LinearLayout brushtheIdentityLayout;
    @BindView(R.id.identity_indo_okbtn)
    Button identityIndoOkbtn;
    @BindView(R.id.identity_indo_layout)
    CardView identityIndoLayout;
    @BindView(R.id.special_service_cardview)
    CardView specialServiceCardview;
    @BindView(R.id.changenew_password_edtext)
    EditText changenewPasswordEdtext;
    @BindView(R.id.changenew_password_nobtn)
    Button changenewPasswordNobtn;
    @BindView(R.id.changenew_password_okbtn)
    Button changenewPasswordOkbtn;
    @BindView(R.id.changenew_password_layout)
    LinearLayout changenewPasswordLayout;
    @BindView(R.id.changenew_password2_edtext)
    EditText changenewPassword2Edtext;
    @BindView(R.id.changenew_password2_nobtn)
    Button changenewPassword2Nobtn;
    @BindView(R.id.changenew_password2_okbtn)
    Button changenewPassword2Okbtn;
    @BindView(R.id.changenew_password2_layout)
    LinearLayout changenewPassword2Layout;
    @BindView(R.id.null_data_ok_btn)
    Button nullDataOkBtn;
    @BindView(R.id.null_data_layout)
    LinearLayout nullDataLayout;


    @BindView(R.id.user_info_id)
    TextView userInfoId;
    @BindView(R.id.user_info_name)
    TextView userInfoName;
    @BindView(R.id.user_info_qfjg)
    TextView userInfoQfjg;
    @BindView(R.id.user_info_jg)
    TextView userInfoJg;
    @BindView(R.id.user_info_ImageView)
    ImageView userInfoImageView;
    @BindView(R.id.printing_layout)
    LinearLayout printingLayout;
    @BindView(R.id.sure_printingpeper_okbtn)
    Button surePrintingpeperOkbtn;
    @BindView(R.id.sure_printingpeper_layout)
    LinearLayout surePrintingpeperLayout;

    private PosFuncs posFuncs;

    OptionsPickerView optionsPickerView;
    List<String> sf_strings = new ArrayList<>();
    private String id_name = "请选择证件类型";
    private String id_num;
    String CardType = "input";
    //二磁信息
    String track2Data = "";
    //三磁信息
    String track3Data = "";

    //55
    String Field55 = "";
    String bindNum = "";
    private String pass_word;
    private String s_number = "";


    private Shell shell = null;
    private BluetoothDevice mDevice = null;
    private static final int REQUEST_ENABLE_BT = 2;
    private boolean bConnected = false;
    private int m_sec1, m_sec2;
    private int m_msec1, m_msec2;
    private String packageName;
    private Calendar c;
    private BluetoothAdapter mAdapter;
    private String sf_name;
    private String sf_num;
    private SFTPUtils sftpUtils;
    private String new_password;
    private String user_num;
    private String run_time;
    private String f39;
    private int num;
    private String rwNUm;
    private String pz_nums;
    private String username;
    private String time;
    private String s_user_name;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_special_service);
        ButterKnife.bind(this);
        this.setBackBtClick(R.id.base_back_btn);
        this.setTitleText(R.id.base_title_text, "(   " + "特殊业务" + "   )");
        packageName = this.getPackageName();
        posFuncs = PosFuncs.getInstace();
        posFuncs.init(this);

        setPickViewData();
        initPackView();
    }

    @OnClick({R.id.special_service_changepassword, R.id.special_service_report,
            R.id.special_service_reversal, R.id.special_service_vunlock,
            R.id.special_service_verify, R.id.special_service_applyfor,
            R.id.verification_identity_noBtn, R.id.verification_identity_okBtn,
            R.id.modification_success_okbtn, R.id.input_lossof_gzBtn,
            R.id.input_lossof_okbtn, R.id.select_certificcate_btn,
            R.id.select_certificcate_okbtn, R.id.input_certificcate_nobtn,
            R.id.input_certificcate_okbtn,
//            R.id.please_input_iccard_okbtn,
            R.id.identity_indo_okbtn,
            R.id.changenew_password_nobtn,
            R.id.changenew_password_okbtn,
            R.id.changenew_password2_nobtn,
            R.id.changenew_password2_okbtn,
            R.id.null_data_ok_btn,
            R.id.sure_printingpeper_okbtn

    })
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.special_service_changepassword:
                //修改密码
                specialServiceHomelayout.setVisibility(View.GONE);
                verificationIdentityLayout.setVisibility(View.VISIBLE);
                infoType = "mmxg";
                break;
            case R.id.special_service_report:
                //口头挂失
                specialServiceHomelayout.setVisibility(View.GONE);
                inputLossofLayout.setVisibility(View.VISIBLE);
                infoType = "gs";
                break;
            case R.id.special_service_reversal:
                //手工冲正
                infoType = "sgcz";
                String make_type = SpUtils.getSPUtil(getApplicationContext()).getString("all_make_type", "");
                if (make_type.equals("qk") || make_type.equals("bzb")) {
                    specialServiceHomelayout.setVisibility(View.GONE);
                    pleaseInputIccardLayout.setVisibility(View.VISIBLE);
                    readCardTest();

//                    runnable = new Runnable() {
//                        @Override
//                        public void run() {
//                            dealingLayout.setVisibility(View.GONE);
//                            modificationSuccessLayout.setVisibility(View.VISIBLE);
//                            modificationSuccessText.setText("冲正成功");
//                        }
//                    };
//                    handler.postDelayed(runnable, 1000);
                } else {
                    specialServiceHomelayout.setVisibility(View.GONE);
                    nullDataLayout.setVisibility(View.VISIBLE);
                }


                break;
            case R.id.special_service_vunlock:
                //密码解锁
                specialServiceHomelayout.setVisibility(View.GONE);
                verificationIdentityLayout.setVisibility(View.VISIBLE);
                infoType = "mmjs";
                break;
            case R.id.special_service_verify:
                //身份核实
                specialServiceHomelayout.setVisibility(View.GONE);
                initshell();
                break;
            case R.id.special_service_applyfor:
                //申请导秘钥
                Toast.makeText(this, "该功能尚未开放，敬请期待", Toast.LENGTH_SHORT).show();
                break;
            case R.id.verification_identity_noBtn:
                //身份核实 取消
                verificationIdentityLayout.setVisibility(View.GONE);
                specialServiceHomelayout.setVisibility(View.VISIBLE);
                break;
            case R.id.verification_identity_okBtn:
                //身份核实 确定

                if (infoType.equals("mmjs")) {
                    verificationIdentityLayout.setVisibility(View.GONE);
                    pleaseInputIccardLayout.setVisibility(View.VISIBLE);
                    readCardTest();
                } else {
                    verificationIdentityLayout.setVisibility(View.GONE);
                    ficationingLayout.setVisibility(View.VISIBLE);
                    readCardTest();

//                    runnable = new Runnable() {
//                        @Override
//                        public void run() {
//                            ficationingLayout.setVisibility(View.GONE);
//                            dealingLayout.setVisibility(View.VISIBLE);
//                            runnable = new Runnable() {
//                                @Override
//                                public void run() {
//
//                                    dealingLayout.setVisibility(View.GONE);
//                                    modificationSuccessLayout.setVisibility(View.VISIBLE);
//                                }
//                            };
//                            handler.postDelayed(runnable, 1000);
//                        }
//                    };
                }
                break;
            case R.id.modification_success_okbtn:
                //修改成功 确定
                modificationSuccessLayout.setVisibility(View.GONE);
                surePrintingpeperLayout.setVisibility(View.VISIBLE);
//                specialServiceHomelayout.setVisibility(View.VISIBLE);
                break;
            case R.id.input_lossof_gzBtn:
                //输入账号 更正
                inputLossofEdtext.setText("");
                break;
            case R.id.input_lossof_okbtn:
                //输入账号 确定
                if (inputLossofEdtext.getText().toString().equals("")) {
                    Toast.makeText(this, "请输入您要挂失的账号", Toast.LENGTH_SHORT).show();
                } else {
                    if (inputLossofEdtext.getText().toString().trim().length() < 15 || inputLossofEdtext.getText().toString().trim().length() > 20) {
                        Toast.makeText(this, "请输入正确的账号", Toast.LENGTH_SHORT).show();
                    } else {
                        bindNum = inputLossofEdtext.getText().toString().trim();
                        inputLossofLayout.setVisibility(View.GONE);
                        ficationingLayout.setVisibility(View.VISIBLE);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                int Num = SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1);
                                Logger.e("第一次获取rz" + Num);
                                excuteVTA(String.valueOf(Num), inputLossofEdtext.getText().toString().trim(), CardType, "", "2");
                                SpUtils.getSPUtil(getApplicationContext()).putInt("s_Num", Num + 1);
                                Logger.e("第二次获取rz" + SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1));

                            }
                        }).start();
                    }
                }
                break;
            case R.id.select_certificcate_btn:
                //选择证件类型
                optionsPickerView.show();
                break;
            case R.id.select_certificcate_okbtn:
                //确定证件类型
                if (id_name.equals("请选择证件类型")) {
                    Toast.makeText(this, "请选择证件类型", Toast.LENGTH_SHORT).show();
                } else {
                    selectCertificcateLayout.setVisibility(View.GONE);
                    inputCertificcateLayout.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.input_certificcate_nobtn:
                //输入证件号 更正
                inputCertificcateEdtext.setText("");
                break;
            case R.id.input_certificcate_okbtn:
                //输入证件号 确定
                if (inputCertificcateEdtext.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请输入证件号", Toast.LENGTH_SHORT).show();
                } else {
                    if (inputCertificcateEdtext.getText().toString().trim().length() < 10) {
                        Toast.makeText(this, "请输入正确的证件号", Toast.LENGTH_SHORT).show();
                    } else {

//                        if (infoType.equals("mmjs")) {
//                            modificationSuccessLayout.setVisibility(View.VISIBLE);
//                            modificationSuccessText.setText("解锁成功");
//                        } else {
                        if (infoType.equals("mmjs")) {
                            dealingLayout.setVisibility(View.VISIBLE);
                            tradeWithCards(0);
                        } else {
                            dealingLayout.setVisibility(View.VISIBLE);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    enterPin(bindNum, 0);
                                }
                            }).start();
                        }


                        inputCertificcateLayout.setVisibility(View.GONE);
                    }

                }
                break;

            case R.id.identity_indo_okbtn:
                //确认身份信息
//                specialServiceCardview.setVisibility(View.VISIBLE);
//                specialServiceHomelayout.setVisibility(View.VISIBLE);
//                identityIndoLayout.setVisibility(View.GONE);
                this.finish();
                break;

            case R.id.changenew_password_nobtn:
                //输入新密码更正
                changenewPasswordEdtext.setText("");
                break;
            case R.id.changenew_password_okbtn:
                //输入新密码确定
                if (changenewPasswordEdtext.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请输入您的密码", Toast.LENGTH_SHORT).show();
                } else {
                    new_password = changenewPasswordEdtext.getText().toString().trim();
                    changenewPasswordLayout.setVisibility(View.GONE);
                    changenewPassword2Layout.setVisibility(View.VISIBLE);
                }
                break;
            case R.id.changenew_password2_nobtn:
                //再次输入密码 更正
                changenewPassword2Edtext.setText("");
                break;
            case R.id.changenew_password2_okbtn:
                //再次输入密码确定
                if (changenewPassword2Edtext.getText().toString().trim().equals("")) {
                    Toast.makeText(this, "请输入您的密码", Toast.LENGTH_SHORT).show();
                } else {
                    String new_password2 = changenewPassword2Edtext.getText().toString().trim();
                    if (!new_password2.equals(new_password)) {
                        Toast.makeText(this, "两次新密码输入不一致，请重新输入", Toast.LENGTH_SHORT).show();
                        changenewPasswordLayout.setVisibility(View.VISIBLE);
                        changenewPassword2Layout.setVisibility(View.GONE);
                        changenewPasswordEdtext.setText("");
                        changenewPassword2Edtext.setText("");

                    } else {
                        changenewPassword2Layout.setVisibility(View.GONE);
                        dealingLayout.setVisibility(View.VISIBLE);
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// HH:mm:ss
                        //获取当前时间
                        Date date = new Date(System.currentTimeMillis());

                        time = simpleDateFormat.format(date);
                        run_time = DateUtil.getCurrentTime(DateUtil.M_TIME_PATTERN);

//                        changepass();
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                num = SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1);
                                Logger.e("第一次获取rz" + num);
                                excuteMMXG(String.valueOf(num), bindNum);
                                SpUtils.getSPUtil(getApplicationContext()).putInt("s_Num", num + 1);
                                Logger.e("第二次获取rz" + SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1));
                            }
                        }).start();
                    }
                }
                break;
            case R.id.null_data_ok_btn:
                //冲正无数据 确定
                this.finish();
                break;
            case R.id.sure_printingpeper_okbtn:
                surePrintingpeperLayout.setVisibility(View.GONE);
                printingLayout.setVisibility(View.VISIBLE);

                if (infoType.equals("sgcz")) {
                    paintsgcz();
                } else if (infoType.equals("gs")) {
                    paintgs();
                } else if (infoType.equals("mmjs")) {
                    paintjs();
                } else {
                    paint();
                }
                break;
        }
    }

    private void paintjs() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                String money = SpUtils.getSPUtil(getApplicationContext()).getString("cz_money", "");

                posFuncs.printerClearBuffer();
                posFuncs.printerAppendLargeTextAlignCenter("烟台银行 通用凭证");
                posFuncs.printerAppendTextline("交易时间 :" + time);
                posFuncs.printerAppendTextline("设备号 :" + Constants.YANTAI_TERMNO);
                posFuncs.printerAppendTextline("操作员 :" + SpUtils.getSPUtil(getApplicationContext()).getString("make_user", ""));

                posFuncs.printerAppendTextline("账号/卡号 :" + bindNum);

                posFuncs.printerAppendTextline("流水号 :" + rwNUm);

                posFuncs.printerAppendTextline("业务类型 :" + "密码解锁");


                posFuncs.printerAppendTextline("户名 :" + username);

                posFuncs.printerAppendTextline("凭证序号 :" + pz_nums);
                posFuncs.printerAppendTextline("客户签字确认 :");

                posFuncs.printerAppendTextline("--------------------------------------");
                posFuncs.printerAppendLargeTextAlignCenter("烟台银行 通用凭证");
                posFuncs.printerAppendTextline("交易时间 :" + time);
                posFuncs.printerAppendTextline("设备号 :" + Constants.YANTAI_TERMNO);
                posFuncs.printerAppendTextline("操作员 :" + SpUtils.getSPUtil(getApplicationContext()).getString("make_user", ""));
                String bindx = bindNum.substring(6, bindNum.length() - 5);
                String bindxs = "*";
                for (int i = 0; i < bindx.length(); i++) {
                    bindxs = bindxs + "*";
                }
                posFuncs.printerAppendTextline("账号/卡号 :" + bindNum.substring(0, 6) + bindxs + bindNum.substring(bindNum.length() - 4, bindNum.length()));

                posFuncs.printerAppendTextline("流水号 :" + rwNUm);

                posFuncs.printerAppendTextline("业务类型 :" + "密码解锁");


                posFuncs.printerAppendTextline("户名 :" + "*" + s_user_name);

                posFuncs.printerAppendTextline("凭证序号 :" + pz_nums);
                posFuncs.printerAppendTextline("客户签字确认 :");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");


                posFuncs.startPrint(new PosCallbacks.PrintCallbacaks() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(SpecialServiceActivity.this, "打印成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onFailed(String error) {
                        if (error.equals("Lack Paper")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(SpecialServiceActivity.this, "请确认打印纸安装正确", Toast.LENGTH_SHORT).show();
                                    surePrintingpeperLayout.setVisibility(View.VISIBLE);
                                    printingLayout.setVisibility(View.GONE);
                                }
                            });
                        }
                    }
                });
            }
        }.start();
    }

    private void paintsgcz() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                String money = SpUtils.getSPUtil(getApplicationContext()).getString("cz_money", "");

                posFuncs.printerClearBuffer();
                posFuncs.printerAppendLargeTextAlignCenter("烟台银行 通用凭证");
                posFuncs.printerAppendTextline("交易时间 :" + time);
                posFuncs.printerAppendTextline("设备号 :" + Constants.YANTAI_TERMNO);
                posFuncs.printerAppendTextline("操作员 :" + SpUtils.getSPUtil(getApplicationContext()).getString("make_user", ""));

                posFuncs.printerAppendTextline("账号/卡号 :" + bindNum);

                posFuncs.printerAppendTextline("流水号 :" + rwNUm);

                posFuncs.printerAppendTextline("业务类型 :" + "手工冲正");


                posFuncs.printerAppendTextline("户名 :" + username);
                posFuncs.printerAppendTextline("交易金额 :" + money);
                posFuncs.printerAppendTextline("凭证序号 :" + pz_nums);
                posFuncs.printerAppendTextline("客户签字确认 :");

                posFuncs.printerAppendTextline("--------------------------------------");
                posFuncs.printerAppendLargeTextAlignCenter("烟台银行 通用凭证");
                posFuncs.printerAppendTextline("交易时间 :" + time);
                posFuncs.printerAppendTextline("设备号 :" + Constants.YANTAI_TERMNO);
                posFuncs.printerAppendTextline("操作员 :" + SpUtils.getSPUtil(getApplicationContext()).getString("make_user", ""));
                String bindx = bindNum.substring(6, bindNum.length() - 5);
                String bindxs = "*";
                for (int i = 0; i < bindx.length(); i++) {
                    bindxs = bindxs + "*";
                }
                posFuncs.printerAppendTextline("账号/卡号 :" + bindNum.substring(0, 6) + bindxs + bindNum.substring(bindNum.length() - 4, bindNum.length()));

                posFuncs.printerAppendTextline("流水号 :" + rwNUm);

                posFuncs.printerAppendTextline("业务类型 :" + "手工冲正");


                posFuncs.printerAppendTextline("户名 :" + "*" + s_user_name);
                posFuncs.printerAppendTextline("交易金额 :" + money);
                posFuncs.printerAppendTextline("凭证序号 :" + pz_nums);
                posFuncs.printerAppendTextline("客户签字确认 :");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");


                posFuncs.startPrint(new PosCallbacks.PrintCallbacaks() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(SpecialServiceActivity.this, "打印成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onFailed(String error) {
                        if (error.equals("Lack Paper")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(SpecialServiceActivity.this, "请确认打印纸安装正确", Toast.LENGTH_SHORT).show();
                                    surePrintingpeperLayout.setVisibility(View.VISIBLE);
                                    printingLayout.setVisibility(View.GONE);
                                }
                            });
                        }
                    }
                });
            }
        }.start();
    }

    private void paintgs() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                String money = SpUtils.getSPUtil(getApplicationContext()).getString("cz_money", "");

                posFuncs.printerClearBuffer();
                posFuncs.printerAppendLargeTextAlignCenter("烟台银行 通用凭证");
                posFuncs.printerAppendTextline("交易时间 :" + time);
                posFuncs.printerAppendTextline("设备号 :" + Constants.YANTAI_TERMNO);
                posFuncs.printerAppendTextline("操作员 :" + SpUtils.getSPUtil(getApplicationContext()).getString("make_user", ""));

                posFuncs.printerAppendTextline("账号/卡号 :" + bindNum);

                posFuncs.printerAppendTextline("流水号 :" + rwNUm);

                posFuncs.printerAppendTextline("业务类型 :" + "口头挂失");


                posFuncs.printerAppendTextline("户名 :" + username);

                posFuncs.printerAppendTextline("凭证序号 :" + pz_nums);
                posFuncs.printerAppendTextline("客户签字确认 :");

                posFuncs.printerAppendTextline("--------------------------------------");
                posFuncs.printerAppendLargeTextAlignCenter("烟台银行 通用凭证");
                posFuncs.printerAppendTextline("交易时间 :" + time);
                posFuncs.printerAppendTextline("设备号 :" + Constants.YANTAI_TERMNO);
                posFuncs.printerAppendTextline("操作员 :" + SpUtils.getSPUtil(getApplicationContext()).getString("make_user", ""));
                String bindx = bindNum.substring(6, bindNum.length() - 5);
                String bindxs = "*";
                for (int i = 0; i < bindx.length(); i++) {
                    bindxs = bindxs + "*";
                }
                posFuncs.printerAppendTextline("账号/卡号 :" + bindNum.substring(0, 6) + bindxs + bindNum.substring(bindNum.length() - 4, bindNum.length()));

                posFuncs.printerAppendTextline("流水号 :" + rwNUm);

                posFuncs.printerAppendTextline("业务类型 :" + "口头挂失");


                posFuncs.printerAppendTextline("户名 :" + "*" + s_user_name);

                posFuncs.printerAppendTextline("凭证序号 :" + pz_nums);
                posFuncs.printerAppendTextline("客户签字确认 :");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");


                posFuncs.startPrint(new PosCallbacks.PrintCallbacaks() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(SpecialServiceActivity.this, "打印成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onFailed(String error) {
                        if (error.equals("Lack Paper")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(SpecialServiceActivity.this, "请确认打印纸安装正确", Toast.LENGTH_SHORT).show();
                                    surePrintingpeperLayout.setVisibility(View.VISIBLE);
                                    printingLayout.setVisibility(View.GONE);
                                }
                            });
                        }
                    }
                });
            }
        }.start();
    }


    private void paint() {
        new Thread() {
            @Override
            public void run() {
                super.run();
                posFuncs.printerClearBuffer();
                posFuncs.printerAppendLargeTextAlignCenter("烟台银行 通用凭证");
                posFuncs.printerAppendTextline("交易时间 :" + time);
                posFuncs.printerAppendTextline("设备号 :" + Constants.YANTAI_TERMNO);
                posFuncs.printerAppendTextline("操作员 :" + SpUtils.getSPUtil(getApplicationContext()).getString("make_user", ""));

                posFuncs.printerAppendTextline("账号/卡号 :" + bindNum);

                posFuncs.printerAppendTextline("流水号 :" + rwNUm);

                posFuncs.printerAppendTextline("业务类型 :" + "密码修改");


                posFuncs.printerAppendTextline("户名 :" + username);
                posFuncs.printerAppendTextline("凭证序号 :" + pz_nums);
                posFuncs.printerAppendTextline("客户签字确认 :");

                posFuncs.printerAppendTextline("--------------------------------------");
                posFuncs.printerAppendLargeTextAlignCenter("烟台银行 通用凭证");
                posFuncs.printerAppendTextline("交易时间 :" + time);
                posFuncs.printerAppendTextline("设备号 :" + Constants.YANTAI_TERMNO);
                posFuncs.printerAppendTextline("操作员 :" + SpUtils.getSPUtil(getApplicationContext()).getString("make_user", ""));
                String bindx = bindNum.substring(6, bindNum.length() - 5);
                String bindxs = "*";
                for (int i = 0; i < bindx.length(); i++) {
                    bindxs = bindxs + "*";
                }
                posFuncs.printerAppendTextline("账号/卡号 :" + bindNum.substring(0, 6) + bindxs + bindNum.substring(bindNum.length() - 4, bindNum.length()));

                posFuncs.printerAppendTextline("流水号 :" + rwNUm);

                posFuncs.printerAppendTextline("业务类型 :" + "密码修改");


                posFuncs.printerAppendTextline("户名 :" + "*" + s_user_name);
                posFuncs.printerAppendTextline("凭证序号 :" + pz_nums);
                posFuncs.printerAppendTextline("客户签字确认 :");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");
                posFuncs.printerAppendTextline("");


                posFuncs.startPrint(new PosCallbacks.PrintCallbacaks() {
                    @Override
                    public void onSuccess() {
                        Toast.makeText(SpecialServiceActivity.this, "打印成功", Toast.LENGTH_SHORT).show();
                        finish();
                    }

                    @Override
                    public void onFailed(String error) {
                        if (error.equals("Lack Paper")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Toast.makeText(SpecialServiceActivity.this, "请确认打印纸安装正确", Toast.LENGTH_SHORT).show();
                                    surePrintingpeperLayout.setVisibility(View.VISIBLE);
                                    printingLayout.setVisibility(View.GONE);
                                }
                            });
                        }
                    }
                });
            }
        }.start();
    }

    /**
     * 开始读取身份信息
     */
    private class GetDataThread implements Runnable {
        private String data;
        private byte[] cardInfo = new byte[256];
        private int count = 0;
        private Message msg;//主要改了这个地方，好像启作用了
        private String wltPath = "";
        private String termBPath = "";
        private boolean bRet = false;


        public GetDataThread() {
        }

        public void run() {
            globalEnum ge = globalEnum.GetIndentiyCardData_GetData_Failed;
            try {
                Thread.sleep(2000);

                globalEnum gFindCard = globalEnum.NONE;
                long start = System.currentTimeMillis();
                while (!bStop) {
                    data = null;//
                    msg = handler.obtainMessage(71, data);//发送消息
                    handler.sendMessage(msg);
                    bRet = shell.SearchCard();
                    if (bRet) {
                        data = null;//
                        msg = handler.obtainMessage(1, data);//发送消息
                        handler.sendMessage(msg);
                        bRet = shell.SelectCard();
                        if (bRet) {
                            data = null;//
                            msg = handler.obtainMessage(2, data);//发送消息
                            handler.sendMessage(msg);
                            //Thread.sleep(100);

                            int nRet = shell.ReadCardWithFinger();//nRet 1:二代证无指纹 2：二代证包含指纹
                            if (nRet > 0) {
                                data = null;//
                                byte[] fingerBuff = new byte[1024];
                                byte[] wltBuff = new byte[1024];
                                if (nRet == 2) {
                                    bRet = shell.GetFingerData(fingerBuff);
                                    //	Log.w("ComShell","fingerData is:"+Util.toHexStringNoSpace(fingerBuff, 1024));
                                }

                                msg = handler.obtainMessage(3, data);//发送消息
                                handler.sendMessage(msg);

                                cardInfo = shell.GetCardInfoBytes();
                                if (shell.GetCardTypeFlag(cardInfo) == 0) {//0时为二代证信息
                                    data = String.format(
                                            "姓名：%s 性别：%s 民族：%s 出生日期：%s 住址：%s 身份证号：%s 签发机关：%s 有效期：%s-%s",
                                            shell.GetName(cardInfo), shell.GetGender(cardInfo), shell.GetNational(cardInfo),
                                            shell.GetBirthday(cardInfo), shell.GetAddress(cardInfo),
                                            shell.GetIndentityCard(cardInfo), shell.GetIssued(cardInfo),
                                            shell.GetStartDate(cardInfo), shell.GetEndDate(cardInfo));
                                    if (nRet == 2) {
                                        data = data + "\r\n" + "指纹特征值已读取";
                                    } else if (nRet == 1) {
                                        data = data + "\r\n" + "不包含指纹";
                                    }
                                    sf_name = shell.GetName(cardInfo);
                                    sf_num = shell.GetIndentityCard(cardInfo);
                                } else if (shell.GetCardTypeFlag(cardInfo) == 1) {//1时为外国人居住证信息
                                    data = String.format(
                                            "英文名字：%s 中文名字：%s 性别：%s 国籍代码：%s 国籍名称：%s 出生日期：%s 身份证号：%s 签发机关：%s 有效期：%s-%s",
                                            shell.GetFEName(cardInfo), shell.GetFCName(cardInfo), shell.GetFGender(cardInfo), shell.GetFCountryCode(cardInfo), shell.GetFCountryName(cardInfo),
                                            shell.GetFBirthday(cardInfo),
                                            shell.GetFIndentityCard(cardInfo), shell.GetFIssued(cardInfo),
                                            shell.GetFStartDate(cardInfo), shell.GetFEndDate(cardInfo));
                                    if (nRet == 2) {
                                        data = data + "\r\n" + "指纹特征值已读取";
                                    } else if (nRet == 1) {
                                        data = data + "\r\n" + "不包含指纹";
                                    }
                                } else {
                                    msg = handler.obtainMessage(6, data);//读卡失败
                                    handler.sendMessage(msg);    //readC
                                    break;
                                }
                                msg = handler.obtainMessage(0, data);//发送消息
                                handler.sendMessage(msg);

                                //	Log.w("777"," shell.GetEndDate(cardInfo) is:"+ shell.GetEndDate(cardInfo));
                                byte[] bmpBuff = new byte[38862];
                                boolean bRet = shell.GetWltData(wltBuff);
                                if (bRet) {
                                    Log.w("ComShell", "packageName is :" + packageName);
                                    nRet = shell.GetPicByBuff(packageName, wltBuff, bmpBuff);
                                    Log.w("ComShell", "GetPicByBuff nRet is:" + nRet);
                                    if (nRet == 1) {
                                        Bitmap bm = BitmapFactory.decodeByteArray(
                                                bmpBuff, 0, 38862);
                                        if (bm != null) {
                                            msg = handler.obtainMessage(100, bm);//发送消息
                                            handler.sendMessage(msg);
                                        }
                                    } else if (nRet == -5) {
                                        msg = handler.obtainMessage(101, data);//发送消息
                                        handler.sendMessage(msg);
                                    } else if (nRet == -1) {
                                        msg = handler.obtainMessage(102, data);//发送消息
                                        handler.sendMessage(msg);
                                    }
                                    //break;//0316  调试用，所以增加
                                }
                            } else {
                                msg = handler.obtainMessage(6, data);//发送消息
                                handler.sendMessage(msg);    //readCard error
                            }
                        } else {
                            msg = handler.obtainMessage(5, data);//发送消息
                            handler.sendMessage(msg);    //selectCard error
                        }
                    } else {
                        msg = handler.obtainMessage(4, data);//发送消息
                        handler.sendMessage(msg);    //searchCard error
                    }
                    Thread.sleep(50);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    public Handler handler = new Handler() {//处理UI绘制
        private String data;
        private Bitmap bm;
        private int t_sec1, t_sec2;
        private int t_msec1, t_msec2;

        private Calendar t;

        @SuppressWarnings("unchecked")
        @Override
        public void handleMessage(Message msg) {//M_ERROR  M_VALIDATE_ERROR I_ERROR I_VALIDATE_ERROR
            switch (msg.what) {                    //C_ERROR  C_VALIDATE_ERROR D_ERROR D_VALIDATE_ERROR
                case 0:
                    data = (String) msg.obj;
                    if (data == null) {
                    } else {
                        //mInfoView.clear();
                        t = Calendar.getInstance();
                        t_sec2 = t.get(Calendar.SECOND);
                        t_msec2 = t.get(Calendar.MILLISECOND);
                        int d = t_sec2 - t_sec1;
                        int md = t_msec2 - t_msec1;
                        if (d < 0)
                            d = d + 60;
                        if (md < 0) {
                            d = d - 1;
                            md = md + 1000;
                        }
                        Logger.e(data);
                        brushtheIdentityLayout.setVisibility(View.GONE);
                        dealingLayout.setVisibility(View.VISIBLE);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                int Num = SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1);
                                Logger.e("第一次获取rz" + Num);
                                excuteSFRZ(String.valueOf(Num));
                                SpUtils.getSPUtil(getApplicationContext()).putInt("s_Num", Num + 1);
                                Logger.e("第二次获取rz" + SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1));
                            }
                        }).start();
                    }
                    break;
                case 71:
                    t = Calendar.getInstance();
                    t_sec1 = t.get(Calendar.SECOND);
                    t_msec1 = t.get(Calendar.MILLISECOND);
                    break;
                case 100:

                    //  deleteFile("zp.bmp");

                    break;
                case 101:
                    Toast.makeText(SpecialServiceActivity.this, "照片解码授权文件不正确", Toast.LENGTH_SHORT).show();
                    break;
                case 102:
                    Toast.makeText(SpecialServiceActivity.this, "照片原始数据不正确", Toast.LENGTH_SHORT).show();


                    break;
                case 1:


                    //mInfoView.add("SearchCard ok");
                    break;
                case 4:
//			mInfoView.clear();
//			mInfoView.add("SearchCard error");
                    //mInfoView.add("正在寻卡...");
                    break;
                case 5:
                    Toast.makeText(SpecialServiceActivity.this, "SelectCard error", Toast.LENGTH_SHORT).show();

                    break;
                case 6:
                    Toast.makeText(SpecialServiceActivity.this, "ReadCard error", Toast.LENGTH_SHORT).show();
                    break;
                case 87:
                    Toast.makeText(SpecialServiceActivity.this, "读卡初始化中，请稍候...", Toast.LENGTH_SHORT).show();
                    break;
                case 88:
                    Toast.makeText(SpecialServiceActivity.this, "机具信息监听中...", Toast.LENGTH_SHORT).show();
                    break;
                case 99:
                    break;
                default:
                    break;
            }
        }
    };

    /**
     * 身份验证器初始化并进行操作
     */
    private void initshell() {
        mAdapter = BluetoothAdapter.getDefaultAdapter();

        if (!mAdapter.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        c = Calendar.getInstance();
        m_sec1 = c.get(Calendar.SECOND);
        m_msec1 = c.get(Calendar.MILLISECOND);
        Set<BluetoothDevice> pairedDevices = mAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            for (BluetoothDevice device : pairedDevices) {
                String str;
                str = device.getName().substring(0, 3);
                Log.w("pairedDevices", "device.getName().substring(0, 1) is:" + str);
                if ((str.equalsIgnoreCase("SYN")) || (str.equalsIgnoreCase("SS-")) || (str.equalsIgnoreCase("PSB"))) {
                    Log.w("onCreate", "device.getName() is SYNTHESIS");
                    mDevice = device;
                } else   //是否能进入Else
                {
                    Log.w("onCreate", "device.getName() is not SYNTHESIS");
                    boolean bAllNum = false;
                    if (device.getName().length() > 9) {
                        str = device.getName().substring(0, 10);
                        bAllNum = str.matches("[0-9]+");
                        if (bAllNum == true) {
                            mDevice = device;
                        }
                    }
                }
                Logger.e(device.getName() + "====" + device.getAddress());
            }
            try {
                mAdapter.cancelDiscovery();

                if (mDevice != null)
                    shell = new Shell(this.getApplicationContext(), mDevice);
                c = Calendar.getInstance();
                m_sec2 = c.get(Calendar.SECOND);
                m_msec1 = c.get(Calendar.MILLISECOND);
                int d = m_sec2 - m_sec1;
                int md = m_msec2 - m_msec1;
                if (d < 0)
                    d = d + 60;
                if (md < 0)
                    md = md + 1000;
                //	mInfoView.add("connect timeee is:  "+d+"."+md+"s");

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Log.w("test", "Socket connect error！");
                Toast.makeText(this, "与机具建立连接失败，请尝试重新启动应用程序!", Toast.LENGTH_SHORT).show();
            }
            Log.w("test", "Socket connect OK！");
        }


        globalEnum ge = globalEnum.NONE;
        Log.w("TestJarActivity", "In ButtonInitOnClick shell 00");
        //mInfoView.add("ButtonInitOnClick");
        if (shell == null) {
            Log.w("TestJarActivity", "In ButtonInitOnClick shell is null");
            try {
                if (mDevice == null) {

                    Toast.makeText(this, "与机具建立连接失败，请检查蓝牙配置", Toast.LENGTH_SHORT).show();
                    Log.w("TestJarActivity", "In ButtonInitOnClick shell 212");
                    return;
                }
                shell = new Shell(getApplicationContext(), mDevice);
                Logger.e("TestJarActivity" + "In ButtonInitOnClick shell 11");
            } catch (Exception e) {
                Logger.e("TestJarActivity" + "In ButtonInitOnClick shell 22");
                e.printStackTrace();
            }
        }

        try {
            if (shell.Register()) {
                //0316 btnRegist.setEnabled(false);
                Toast.makeText(this, "取机具编号成功！", Toast.LENGTH_SHORT).show();
                ge = shell.Init();
                if (ge == globalEnum.INITIAL_SUCCESS) {


                    Toast.makeText(this, "建立连接成功", Toast.LENGTH_SHORT).show();
                    brushtheIdentityLayout.setVisibility(View.VISIBLE);

                    new Thread(new GetDataThread()).start();
                } else {
                    shell.EndCommunication();//0316
                    specialServiceHomelayout.setVisibility(View.VISIBLE);
                    Toast.makeText(this, "与机具建立连接失败，请检查蓝牙配置", Toast.LENGTH_SHORT).show();
                }
            } else {
                specialServiceHomelayout.setVisibility(View.VISIBLE);
                Toast.makeText(this, "与机具建立连接失败，请检查蓝牙配置", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    /**
     * 账户验证
     */
    public void excuteVTA(String transn, String bindNum, String CardTYpe, String track2Data, String h_pass) {
        String c_bin_info = SpUtils.getSPUtil(getApplicationContext()).getString("c_bin_info", "null");
        Gson gson = new Gson();
        List<CardBinInfo_bean> beans = gson.fromJson(c_bin_info, new TypeToken<List<CardBinInfo_bean>>() {
        }.getType());
        IsoMessage msg = null;
        VTAInterface inter = new VTAInterface();
        msg = inter.packRequest(bindNum, beans, transn, track2Data, CardTYpe, h_pass, s_number);
        excuteRequest(msg, "zhrz");
    }

    /**
     * 账户挂失
     */
    public void excuteGS(String transn, String bindNum) {
        IsoMessage msg = null;
        RTLOInterface inter = new RTLOInterface();
        msg = inter.packRequest(transn, bindNum, pass_word, CardType, id_num, inputCertificcateEdtext.getText().toString().trim(), run_time);
        excuteRequest(msg, "gs");
    }

    /**
     * 密码修改
     */
    public void excuteMMXG(String transn, String bindNum) {
        String c_bin_info = SpUtils.getSPUtil(getApplicationContext()).getString("c_bin_info", "null");
        Gson gson = new Gson();
        List<CardBinInfo_bean> beans = gson.fromJson(c_bin_info, new TypeToken<List<CardBinInfo_bean>>() {
        }.getType());
        IsoMessage msg = null;
        PWDInterface inter = new PWDInterface();
        msg = inter.packRequest(transn, bindNum, pass_word, new_password, beans, CardType, track2Data, track3Data, s_number, Field55, run_time);
        excuteRequest(msg, "mmxg");
    }

    /**
     * 身份认证
     *
     * @param transn
     */
    public void excuteSFRZ(String transn) {

        IsoMessage msg = null;
        SFInterface inter = new SFInterface();
        msg = inter.packRequest(transn, sf_num, sf_name);
        excuteRequest(msg, "sfrx");
    }

    /**
     * 密码解锁
     */
    private void excuteJS(String transn) {
        Logger.e(track2Data);
        String c_bin_info = SpUtils.getSPUtil(getApplicationContext()).getString("c_bin_info", "null");
        Gson gson = new Gson();
        List<CardBinInfo_bean> beans = gson.fromJson(c_bin_info, new TypeToken<List<CardBinInfo_bean>>() {
        }.getType());
        IsoMessage msg = null;
        TPUInstall inter = new TPUInstall();
        msg = inter.packRequest(transn, bindNum, pass_word, beans, CardType, track2Data, id_num, inputCertificcateEdtext.getText().toString().trim(), s_number, Field55, user_num, run_time);
        excuteRequest(msg, "mmjs");
    }

    /**
     * 冲正
     */
    public void excuteCZ(String transn) {
        String cz_num = SpUtils.getSPUtil(getApplicationContext()).getString("cz_Num", "");
        String cz_time = SpUtils.getSPUtil(getApplicationContext()).getString("cz_time", "");
        String money = SpUtils.getSPUtil(getApplicationContext()).getString("cz_money", "");
        String injon_bind = SpUtils.getSPUtil(getApplicationContext()).getString("injon_bind", "");

        IsoMessage msg = null;
        CZInterface inter = new CZInterface();
        String make_type = SpUtils.getSPUtil(getApplicationContext()).getString("all_make_type", "");
        if (make_type.equals("qk")) {
            msg = inter.packRequest(bindNum, bindNum, Constants.DEMO_F102, cz_num, cz_time, run_time, transn, track2Data, track3Data, CardType, pass_word, String.valueOf(1), Field55, money, s_number);
        } else {
            msg = inter.packRequest(bindNum, bindNum, injon_bind, cz_num, cz_time, run_time, transn, track2Data, track3Data, CardType, pass_word, String.valueOf(1), Field55, money, s_number);
        }
        excuteRequest(msg, "sgcz");
    }


    /**
     * 调取键盘
     */
    private void enterPin(final String bindNum, final double money) {
        Logger.e(money + "");
        new Thread() {
            @Override
            public void run() {
                posFuncs.enterPin(new PosCallbacks.EnterPinCallbacks() {

                    private String password;

                    @Override
                    public void onSuccess(final String enc, boolean is_no_pin) {
                        if (!is_no_pin) {
                            Logger.e("enc" + enc);
                            String pin = null;
                            try {
                                pin = PinPad.getPin(bindNum, enc);
                                pass_word = pin;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
//                            if (infoType.equals("mmxg")) {
//                                //密码修改
//                                try {
//                                    pin = PinPad.getPin(bindNum, enc);
//                                    password = pin;
//                                } catch (Exception e) {
//                                    e.printStackTrace();
//                                }
//                                if (xg_pass_word1.equals("")) {
//                                    xg_pass_word1 = password;
//                                    enterPin(bindNum, 0);
//                                } else if (xg_pass_word2.equals("")) {
//                                    xg_pass_word2 = password;
//                                    Logger.e("aaaaaaaaaaaaaa");
//                                    if (!xg_pass_word1.equals(xg_pass_word2)) {
//                                        Toast.makeText(SpecialServiceActivity.this, "两次密码输入不一致，请重新输入", Toast.LENGTH_SHORT).show();
//                                        ficationingLayout.setVisibility(View.GONE);
//                                        dealingLayout.setVisibility(View.VISIBLE);
//                                        specialServiceHomelayout.setVisibility(View.VISIBLE);
//                                    } else {
//                                        Logger.e("vvvvvvvvvvvv");
//                                        ficationingLayout.setVisibility(View.GONE);
//                                        dealingLayout.setVisibility(View.GONE);
//
//                                    }
//                                }
                            if (infoType.equals("gs")) {
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// HH:mm:ss
                                //获取当前时间
                                Date date = new Date(System.currentTimeMillis());

                                time = simpleDateFormat.format(date);
                                run_time = DateUtil.getCurrentTime(DateUtil.M_TIME_PATTERN);
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        num = SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1);
                                        Logger.e("第一次获取rz" + num);
                                        excuteGS(String.valueOf(num), inputLossofEdtext.getText().toString().trim());
                                        SpUtils.getSPUtil(getApplicationContext()).putInt("s_Num", num + 1);
                                        Logger.e("第二次获取rz" + SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1));

                                    }
                                }).start();
                            }
                        } else {
                            Logger.e("enc" + enc);
                        }
                    }

                    @Override
                    public void onFail(String error) {
                        Toast.makeText(SpecialServiceActivity.this, "交易结束", Toast.LENGTH_SHORT).show();
                        if (!error.equals(null)) {
                            finish();
                        }

                    }

                    @Override
                    public void onInput(int input_num) {
                        Log.e("", String.valueOf(input_num));
                    }
                }, bindNum, (int) money);
            }
        }.start();
    }


    private void tradeWithCards(final double money) {
        Logger.e(money + "");
        PinPad.initPinPad(posFuncs);
        new Thread() {
            @Override
            public void run() {

                posFuncs.cardReaderConfig(true, true, true);
                posFuncs.emvTransStart(new PosCallbacks.EmvTransStartCallbacks() {

                    @Override
                    public void onDetectCard(String type) {
                        CardType = type;
                        Logger.e(type + "type");
                    }

                    @Override
                    public void onConfirmCardInfo(final String pan) {
                        bindNum = pan;
                        Logger.e(pan);
                        posFuncs.emvConfirmCardInfo(EmvConstants.CONFIRM_OK);

                    }

                    @Override
                    public void onOlinePinEntered(String enc, boolean is_no_pin) {
                        if (!is_no_pin) {

                            try {
                                String pin = PinPad.getPin(bindNum, enc);
                                pass_word = pin;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            Toast.makeText(getApplicationContext(), "请输入密码", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onSuccess(Bundle data) {


                        String channel = data.getString(EmvConstants.CHANNEL);
                        if (EmvConstants.CHANNEL_MAGCARD.equals(channel)) {
                            track2Data = data.getString(EmvConstants.TRACK2);
                            track3Data = data.getString(EmvConstants.TRACK3);
                        } else if (EmvConstants.CHANNEL_ICC.equals(channel)) {
                            track2Data = Utils.formatField57(Utils.getValueFromIccData("57", data.getString(EmvConstants.FEILD_55)));
                            s_number = Utils.getValueFromIccData("5f34", data.getString(EmvConstants.FEILD_55));

                            String ac_type = data.getString(EmvConstants.AC_TYPE);
                            Logger.e("ac_type" + ac_type);
                            Logger.e("Ac Type: " + data.getString(EmvConstants.AC_TYPE) + "\n");
                            Logger.e("Field 55: " + data.getString(EmvConstants.FEILD_55) + "\n");
                            String[] tags =
                                    {
                                            "9F26", "9F27", "9F10", "9F37", "9F36", "95",
                                            "9A", "9C", "9F02", "5F2A", "82", "9F1A", "9F03", "9F33", "9F34", "9F35",
                                            "9F1E", "84", "9F09", "9F41"
                                    };
                            Field55 = Utils.getField55(tags, data.getString(EmvConstants.FEILD_55));
                            Logger.e("f55" + Field55);
                            if (EmvConstants.AC_TYPE_ARQC.equals(ac_type)) {

                                Bundle bundle = new Bundle();
                                bundle.putString(EmvConstants.RESPONSE_CODE, "3030");
                                posFuncs.emvOnlineResult(new PosCallbacks.EmvOnlineResultCallbacks() {
                                    @Override
                                    public void onSuccess(Bundle data) {
                                        Logger.e("Ac Type: " + data.getString(EmvConstants.AC_TYPE) + "\n");
                                        Logger.e("Field 55: " + data.getString(EmvConstants.FEILD_55) + "\n");

                                    }

                                    @Override
                                    public void onFailed(String error) {

                                    }
                                }, bundle);
                            } else {

                            }
                        } else if (EmvConstants.CHANNEL_ICCL.equals(channel)) {
                            Logger.e("Ac Type: " + data.getString(EmvConstants.AC_TYPE) + "\n");
                            Logger.e("Field 55: " + data.getString(EmvConstants.FEILD_55) + "\n");
                        }
                        if (infoType.equals("mmxg")) {
//                            enterPin(bindNum, 0);
                            dealingLayout.setVisibility(View.GONE);
                            changenewPasswordLayout.setVisibility(View.VISIBLE);
                        } else if (infoType.equals("mmjs")) {
                            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// HH:mm:ss
                            //获取当前时间
                            Date date = new Date(System.currentTimeMillis());

                            time = simpleDateFormat.format(date);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    run_time = DateUtil.getCurrentTime(DateUtil.M_TIME_PATTERN);
                                    num = SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1);
                                    Logger.e("第一次获取rz" + num);
                                    excuteJS(String.valueOf(num));
                                    SpUtils.getSPUtil(getApplicationContext()).putInt("s_Num", num + 1);
                                    Logger.e("第二次获取rz" + SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1));

                                }
                            }).start();
                        } else if (infoType.equals("sgcz")) {
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");// HH:mm:ss
                                    //获取当前时间
                                    Date date = new Date(System.currentTimeMillis());

                                    time = simpleDateFormat.format(date);
                                    run_time = DateUtil.getCurrentTime(DateUtil.M_TIME_PATTERN);

                                    num = SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1);
                                    Logger.e("第一次获取rz" + num);
                                    excuteCZ(String.valueOf(num));
                                    SpUtils.getSPUtil(getApplicationContext()).putInt("s_Num", num + 1);
                                    Logger.e("第二次获取rz" + SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1));

                                }
                            }).start();
                        }
                    }

                    @Override
                    public void onFailed(String error) {

                    }
                }, (int) money, 0);
            }
        }.start();
    }

    /**
     * 读取卡
     */
    private void readCardTest() {


        new Thread(new Runnable() {
            @Override
            public void run() {
                posFuncs.cardReaderConfig(true, true, true);

                posFuncs.emvSimpleFlow(new PosCallbacks.EmvTransStartCallbacks() {
                    @Override
                    public void onDetectCard(String type) {
                        CardType = type;
                        Log.e("", type);
                        if (infoType.equals("mmjs") || infoType.equals("sgcz")) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    pleaseInputIccardLayout.setVisibility(View.GONE);
                                    ficationingLayout.setVisibility(View.VISIBLE);
                                }
                            });
                        }

                    }

                    @Override
                    public void onConfirmCardInfo(String pan) {
                        Log.e("", pan);
                        bindNum = pan;
                        Toast.makeText(getApplicationContext(), pan, Toast.LENGTH_SHORT).show();
                        posFuncs.emvConfirmCardInfo(EmvConstants.CONFIRM_OK);

                    }

                    @Override
                    public void onOlinePinEntered(String enc, boolean is_no_pin) {

                    }

                    @Override
                    public void onSuccess(Bundle data) {
                        if (!data.isEmpty()) {
                            if (CardType.equals("MAG Card")) {
                                track2Data = data.getString(EmvConstants.TRACK2);
                                track3Data = data.getString(EmvConstants.TRACK3);
                                Logger.e("MAG Card");
                            } else {
                                Logger.e("ic Card");
                                track2Data = Utils.formatField57(Utils.getValueFromIccData("57", data.getString(EmvConstants.FEILD_55)));
                                s_number = Utils.getValueFromIccData("5f34", data.getString(EmvConstants.FEILD_55));

                            }
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    int Num = SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1);
                                    Logger.e("第一次获取rz" + Num);
                                    excuteVTA(String.valueOf(Num), bindNum, CardType, track2Data, "1");
                                    SpUtils.getSPUtil(getApplicationContext()).putInt("s_Num", Num + 1);
                                    Logger.e("第二次获取rz" + SpUtils.getSPUtil(getApplicationContext()).getInt("s_Num", 1));

                                }
                            }).start();

                        } else {
                            Logger.e("data.isEmpty()");
                        }
                    }

                    @Override
                    public void onFailed(String error) {
                        Logger.e(error);
                        Toast.makeText(SpecialServiceActivity.this, "请插入卡", Toast.LENGTH_SHORT).show();
                    }
                });
            }
        }).start();


    }


    private void excuteRequest(IsoMessage msg, final String op_type) {

        byte[] data = msg.writeData();
        // ��д����ͷ��7�򳤶�ֵ
        int hlen = Constants.ATMP_HEADER_LENGTH;
        int bodylen = data.length - hlen;
        String headF7 = ServiceCommon.appendZero(bodylen, 4);
        System.arraycopy(headF7.getBytes(), 0, data, 28, 4);
        // ����MAC
        if (msg.getField(128) != null) {
//            int start = hlen;
//            int length = data.length - start - 8;
//            byte[] inmac = new byte[length];
//            byte[] outmac = new byte[16];
//            System.arraycopy(data, start, inmac, 0, length);
//
//            Logger.e(Constants.YANTAI_MACKEY);
//            String mackey = Constants.YANTAI_MACKEY;
//            // MAC99�㷨makֻ��Ҫ16�ֽ���Կ
//            if (mackey.length() > 16) {
//                mackey = mackey.substring(0, 16);
//            }
//            DES3.getMacBlock_99(inmac, mackey.getBytes(), outmac);
//            System.arraycopy(outmac, 0, data, data.length - 8, 8);
            int start = hlen;
            int length = data.length - start - 8 ;
            byte[] inmac = new byte[length];
            byte[] outmac = new byte[16];
            System.arraycopy(data, start, inmac, 0, length);
            System.out.println("MAC数据=["+HexT.byteArr2HexStr(inmac)+"]");
            String mackey = Constants.YANTAI_MACKEY;

            if(Constants.isSM){
                // SM4 MAC919算法
                byte[] mkey = HexT.hexstr2ByteArr(mackey);
                String macval = SMS4.sms4MacBlock_919(inmac, mkey);
                outmac = macval.getBytes();
            }else{
                // MAC99算法mak只需要16字节密钥
                if(mackey.length()>16){
                    mackey = mackey.substring(0, 16);
                }
                DES3.getMacBlock_99(inmac, mackey.getBytes(), outmac);
            }

            System.arraycopy(outmac, 0, data, data.length-8, 8);
            System.out.println("请求MAC=["+new String(outmac).substring(0, 8)+"]");
        }
        byte[] send = null;
        // ���ļ��ܣ���������ʱ��ҵ���ױ��뱨�ļ���
        String encflag = msg.getHeadStringValue(4);
        if ("1".equals(encflag)) {
            String tdk = Constants.YANTAI_TDKKEY;
            int lenr = 8 - bodylen % 8;
            byte[] head = new byte[hlen];
            byte[] decdata = new byte[bodylen + lenr];
            System.arraycopy(data, 0, head, 0, hlen);
            System.arraycopy(data, hlen, decdata, 0, bodylen);
            byte[] encdata = DES3.des3Packet(decdata, tdk.getBytes());
            send = new byte[hlen + encdata.length];
            System.arraycopy(head, 0, send, 0, hlen);
            System.arraycopy(encdata, 0, send, hlen, encdata.length);

        }else if ("3".equals(encflag)){
            String tdk = Constants.YANTAI_TDKKEY;
            byte[] tdkey = HexT.hexstr2ByteArr(tdk);
            byte[] h7 = new byte[4];
            System.arraycopy(data, 28, h7, 0, 4);
            int orilen = Integer.parseInt(new String(h7));
            int enclen = data.length-Constants.ATMP_HEADER_LENGTH;
            byte[] head = new byte[Constants.ATMP_HEADER_LENGTH];
            byte[] encdata = new byte[enclen];
            System.arraycopy(data, 0, head, 0, Constants.ATMP_HEADER_LENGTH);
            System.arraycopy(data, Constants.ATMP_HEADER_LENGTH, encdata, 0, enclen);
            byte[] decdata = SMS4.unsms4Packet(encdata, tdkey);

            send = new byte[Constants.ATMP_HEADER_LENGTH+orilen];
            System.arraycopy(head, 0, send, 0, Constants.ATMP_HEADER_LENGTH);
            System.arraycopy(decdata, 0, send, Constants.ATMP_HEADER_LENGTH, orilen);
        }  else {
            send = data;
        }

        CommAdapter adapter = new CommAdapter(Constants.IP, 3551);
        adapter.setHeadlen(4); // ����ͷ��4�ֽ�
        byte[] recv = adapter.doComm(send);

        byte[] recv2 = null;
        byte[] b = new byte[1];
        System.arraycopy(recv, 11, b, 0, 1);
        String rspenc = new String(b);

        if ("1".equals(rspenc)) {
            String tdk = Constants.YANTAI_TDKKEY;
            byte[] h7 = new byte[4];
            System.arraycopy(recv, 28, h7, 0, 4);
            int orilen = Integer.parseInt(new String(h7));
            int enclen = recv.length - Constants.ATMP_HEADER_LENGTH;
            byte[] head = new byte[Constants.ATMP_HEADER_LENGTH];
            byte[] encdata = new byte[enclen];
            System.arraycopy(recv, 0, head, 0, Constants.ATMP_HEADER_LENGTH);
            System.arraycopy(recv, Constants.ATMP_HEADER_LENGTH, encdata, 0, enclen);
            byte[] decdata = DES3.undes3Packet(encdata, tdk.getBytes());

            recv2 = new byte[Constants.ATMP_HEADER_LENGTH + orilen];
            System.arraycopy(head, 0, recv2, 0, Constants.ATMP_HEADER_LENGTH);
            System.arraycopy(decdata, 0, recv2, Constants.ATMP_HEADER_LENGTH, orilen);
        } else {
            recv2 = recv;
        }

        IsoMessage rsp = null;
        MessageFactory<IsoMessage> fac = new MessageFactory<IsoMessage>();
        try {
            rsp = fac.parseMessage(recv2, 32);
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        String respcode = rsp.getStringValue(39);
        if ("00".equals(respcode)) {

            unpackReSpone(rsp, op_type);
//            inter.unpackReSpone(rsp);
        } else if ("96".equals(respcode)) {


        } else {
            f39 = rsp.getStringValue(39);
            if (op_type.equals("mmxg")) {
                Up_RundataUtils up_rundataUtils = new Up_RundataUtils();
                try {
                    up_rundataUtils.packRequest("0100", "700000",
                            "000000000000000", "1", run_time, String.valueOf(num), f39);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (op_type.equals("mmjs")) {
                Up_RundataUtils up_rundataUtils = new Up_RundataUtils();
                try {
                    up_rundataUtils.packRequest("0200", "560000",
                            "000000000000000", "1", run_time, String.valueOf(num), f39);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (op_type.equals("gs")) {
                Up_RundataUtils up_rundataUtils = new Up_RundataUtils();
                try {
                    up_rundataUtils.packRequest("0100", "710000",
                            "000000000000000", "1", run_time, String.valueOf(num), f39);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (op_type.equals("sgcz")) {
                Up_RundataUtils up_rundataUtils = new Up_RundataUtils();
                try {
                    up_rundataUtils.packRequest("0420", "440000",
                            "000000000000000", "3", run_time, String.valueOf(num), f39);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            Logger.e("����ʧ��:[{}]-[{}]" + respcode + rsp.getStringValue(40));
            final IsoMessage finalRsp = rsp;
            SpecialServiceActivity.this.runOnUiThread(new Runnable() {
                @SuppressLint("WrongConstant")
                @Override
                public void run() {
//                    Toast.makeText(getApplicationContext(), finalRsp.getStringValue(40), 5000).show();
                    Toast toast = Toast.makeText(getApplicationContext(), finalRsp.getStringValue(40), Toast.LENGTH_LONG);
                    showMyToast(toast, 5 * 1000);
                }
            });

            this.finish();
        }
    }

    public void showMyToast(final Toast toast, final int cnt) {
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                toast.show();
            }
        }, 0, 3000);
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                toast.cancel();
                timer.cancel();
            }
        }, cnt);
    }

    private void unpackReSpone(IsoMessage response, String op_type) {
        f39 = response.getStringValue(39);
        rwNUm = response.getStringValue(37);
        if (op_type.equals("zhrz")) {
            SpUtils.getSPUtil(getApplicationContext()).putString("all_make_type", "zhrz");
            String f123[] = response.getStringValue(123).split("\\|");
            username = f123[2];
            user_num = f123[4];
            s_user_name = username.substring(1, username.length());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (infoType.equals("mmxg")) {
                        ficationingLayout.setVisibility(View.GONE);
                        dealingLayout.setVisibility(View.VISIBLE);
                        tradeWithCards(0);

                    } else if (infoType.equals("mmjs")) {
                        ficationingLayout.setVisibility(View.GONE);
                        selectCertificcateLayout.setVisibility(View.VISIBLE);
                    } else if (infoType.equals("gs")) {
//                        enterPin(bindNum,0);
                        ficationingLayout.setVisibility(View.GONE);
                        selectCertificcateLayout.setVisibility(View.VISIBLE);
                    } else if (infoType.equals("sgcz")) {
                        ficationingLayout.setVisibility(View.GONE);
                        dealingLayout.setVisibility(View.VISIBLE);
                        tradeWithCards(0);
                    }
                }
            });
        } else if (op_type.equals("gs")) {
            Up_RundataUtils up_rundataUtils = new Up_RundataUtils();
            try {
                up_rundataUtils.packRequest("0100", "710000",
                        "000000000000000", "0", run_time, String.valueOf(num), f39);
            } catch (IOException e) {
                e.printStackTrace();
            }
            PzGetUtils pzGetUtils = new PzGetUtils();
            pz_nums = pzGetUtils.pzutil(getApplication());
            SpUtils.getSPUtil(getApplicationContext()).putString("all_make_type", "gs");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dealingLayout.setVisibility(View.GONE);
                    modificationSuccessLayout.setVisibility(View.VISIBLE);
                    modificationSuccessText.setText("挂失成功");
                }
            });
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");// HH:mm:ss
            Gson gson = new Gson();
            Date date = new Date(System.currentTimeMillis());
            String STAT_DATAALL = SpUtils.getSPUtil(getApplicationContext()).getString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", "");
            List<Summary_Bean> beanalls = gson.fromJson(STAT_DATAALL, new TypeToken<List<Summary_Bean>>() {
            }.getType());
            if (!beanalls.get(0).getKtgs().equals("")) {
                String data[] = beanalls.get(0).getKtgs().split(",");


                Logger.e(Double.parseDouble(data[0]) + "bbbbbbbbbbbbbb");
                int nums = Integer.valueOf(data[1]) + 1;
                String getKtgs = "0" + "," + nums;
                Summary_Bean summary_bean = new Summary_Bean(beanalls.get(0).getZnqk(), beanalls.get(0).getXjhk(), beanalls.get(0).getZzhk(), beanalls.get(0).getYdhf(), beanalls.get(0).getLthf(), beanalls.get(0).getSgcc(), beanalls.get(0).getDzh(), beanalls.get(0).getHzd(), beanalls.get(0).getZhgm(), beanalls.get(0).getLwhc(), getKtgs, "", "", beanalls.get(0).getZhcqy(), beanalls.get(0).getZhgm(), beanalls.get(0).getHnyqy(), beanalls.get(0).getHnyjy());
                beanalls.clear();
                beanalls.add(summary_bean);
                Logger.e(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA");
                SpUtils.getSPUtil(getApplicationContext()).putString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", gson.toJson(beanalls));

            } else {
                int nums = 1;
                String getKtgs = "0" + "," + nums;
                Summary_Bean summary_bean = new Summary_Bean(beanalls.get(0).getZnqk(), beanalls.get(0).getXjhk(), beanalls.get(0).getZzhk(), beanalls.get(0).getYdhf(), beanalls.get(0).getLthf(), beanalls.get(0).getSgcc(), beanalls.get(0).getDzh(), beanalls.get(0).getHzd(), beanalls.get(0).getZhgm(), beanalls.get(0).getLwhc(), getKtgs, "", "", beanalls.get(0).getZhcqy(), beanalls.get(0).getZhgm(), beanalls.get(0).getHnyqy(), beanalls.get(0).getHnyjy());
                beanalls.clear();
                beanalls.add(summary_bean);
                Logger.e(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA");
                SpUtils.getSPUtil(getApplicationContext()).putString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", gson.toJson(beanalls));

            }

        } else if (op_type.equals("mmxg")) {
            Up_RundataUtils up_rundataUtils = new Up_RundataUtils();
            try {
                up_rundataUtils.packRequest("0100", "700000",
                        "000000000000000", "0", run_time, String.valueOf(num), f39);
            } catch (IOException e) {
                e.printStackTrace();
            }

            SpUtils.getSPUtil(getApplicationContext()).putString("all_make_type", "mmxg");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dealingLayout.setVisibility(View.GONE);
                    modificationSuccessLayout.setVisibility(View.VISIBLE);
                    modificationSuccessText.setText("修改成功");
                }
            });
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");// HH:mm:ss
            PzGetUtils pzGetUtils = new PzGetUtils();
            pz_nums = pzGetUtils.pzutil(getApplication());
            Gson gson = new Gson();
            Date date = new Date(System.currentTimeMillis());
            String STAT_DATAALL = SpUtils.getSPUtil(getApplicationContext()).getString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", "");
            List<Summary_Bean> beanalls = gson.fromJson(STAT_DATAALL, new TypeToken<List<Summary_Bean>>() {
            }.getType());
            if (!beanalls.get(0).getZhgm().equals("")) {
                double money;
                String data[] = beanalls.get(0).getZhgm().split(",");


                Logger.e(Double.parseDouble(data[0]) + "bbbbbbbbbbbbbb");
                int nums = Integer.valueOf(data[1]) + 1;
                String getzhgm = "0" + "," + nums;
                Summary_Bean summary_bean = new Summary_Bean(beanalls.get(0).getZnqk(), beanalls.get(0).getXjhk(), beanalls.get(0).getZzhk(), beanalls.get(0).getYdhf(), beanalls.get(0).getLthf(), beanalls.get(0).getSgcc(), beanalls.get(0).getDzh(), beanalls.get(0).getHzd(), getzhgm, beanalls.get(0).getLwhc(), beanalls.get(0).getKtgs(), "", "", beanalls.get(0).getZhcqy(), beanalls.get(0).getZhcjy(), beanalls.get(0).getHnyqy(), beanalls.get(0).getHnyjy());
                beanalls.clear();
                beanalls.add(summary_bean);
                Logger.e(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA");
                SpUtils.getSPUtil(getApplicationContext()).putString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", gson.toJson(beanalls));

            } else {
                int nums = 1;
                String getzhgm = "0" + "," + nums;
                Summary_Bean summary_bean = new Summary_Bean(beanalls.get(0).getZnqk(), beanalls.get(0).getXjhk(), beanalls.get(0).getZzhk(), beanalls.get(0).getYdhf(), beanalls.get(0).getLthf(), beanalls.get(0).getSgcc(), beanalls.get(0).getDzh(), beanalls.get(0).getHzd(), getzhgm, beanalls.get(0).getLwhc(), beanalls.get(0).getKtgs(), "", "", beanalls.get(0).getZhcqy(), beanalls.get(0).getZhcjy(), beanalls.get(0).getHnyqy(), beanalls.get(0).getHnyjy());
                beanalls.clear();
                beanalls.add(summary_bean);
                Logger.e(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA");
                SpUtils.getSPUtil(getApplicationContext()).putString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", gson.toJson(beanalls));

            }


        } else if (op_type.equals("sfrx")) {
            SpUtils.getSPUtil(getApplicationContext()).putString("all_make_type", "sfrx");


            String f123[] = response.getStringValue(123).split("\\|");
            final String name = f123[3];
            final String id = f123[2];
            final String qfjg = f123[5];
            String tp_name = f123[1];
            String f123_1 = f123[0];
            final String jg = f123[4];
            if (f123_1.substring(0, 1).equals("1")) {
//存在图片
                SFTPUtils sftpUtils = new SFTPUtils(Constants.IP, "user", "user");
                String localPath = getExternalFilesDir("exter_test").getPath();

                String remotePath = f123_1.substring(1, f123_1.length()) + tp_name;//远程路径
                sftpUtils.connect();
                Logger.d("连接成功");
                sftpUtils.downloadFile(f123_1.substring(1, f123_1.length()), remotePath, localPath, "test.txt");
                Logger.d("下载成功");
                sftpUtils.disconnect();
                final Bitmap a = getDiskBitmap(localPath + "test.txt");
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                a.compress(Bitmap.CompressFormat.PNG, 100, baos);
                final byte[] bytes = baos.toByteArray();


                clearImageDiskCache(getApplicationContext());
                clearImageMemoryCache(getApplicationContext());
//                String ImageExternalCatchDir=getApplication().getExternalCacheDir()+ ExternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR;
//                deleteFolderFile(ImageExternalCatchDir, true);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        specialServiceCardview.setVisibility(View.GONE);
                        dealingLayout.setVisibility(View.GONE);
                        identityIndoLayout.setVisibility(View.VISIBLE);
                        userInfoId.setText(id);
                        userInfoName.setText(name);
                        if (jg.equals("00")) {
                            userInfoJg.setText("公民身份证号码与姓名一致\n且存在照片");
                        } else if (jg.equals("01")) {
                            userInfoJg.setText("公民身份证号码与姓名一致\n但不存在照片");
                        } else if (jg.equals("02")) {
                            userInfoJg.setText("公民身号码存在 \n但姓名不匹配");
                        } else if (jg.equals("03")) {
                            userInfoJg.setText("公民身份号码不存在");
                        } else if (jg.equals("04")) {
                            userInfoJg.setText("其他错误");
                        } else if (jg.equals("05")) {
                            userInfoJg.setText("输入的参数错误");
                        }
                        userInfoQfjg.setText(qfjg);
                        Glide.with(getApplicationContext()).load(bytes).into(userInfoImageView);
                    }
                });
            } else {
                //不存在图片
                specialServiceCardview.setVisibility(View.GONE);
                userInfoImageView.setVisibility(View.GONE);
                dealingLayout.setVisibility(View.GONE);
                identityIndoLayout.setVisibility(View.VISIBLE);
                userInfoId.setText(id);
                userInfoName.setText(name);
                if (jg.equals("00")) {
                    userInfoJg.setText("公民身份证号码与姓名一致\n且存在照片");
                } else if (jg.equals("01")) {
                    userInfoJg.setText("公民身份证号码与姓名一致\n 但不存在照片");
                } else if (jg.equals("02")) {
                    userInfoJg.setText("公民身号码存在 \n但姓名不匹配");
                } else if (jg.equals("03")) {
                    userInfoJg.setText("公民身份号码不存在");
                } else if (jg.equals("04")) {
                    userInfoJg.setText("其他错误");
                } else if (jg.equals("05")) {
                    userInfoJg.setText("输入的参数错误");
                }
                userInfoQfjg.setText(qfjg);
                userInfoImageView.setVisibility(View.GONE);
            }

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");// HH:mm:ss
            //获取当前时间
            Date date = new Date(System.currentTimeMillis());
            Gson gson = new Gson();
            //汇总查询
            String STAT_DATAALL = SpUtils.getSPUtil(getApplicationContext()).getString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", "");
            List<Summary_Bean> beanalls = gson.fromJson(STAT_DATAALL, new TypeToken<List<Summary_Bean>>() {
            }.getType());
            if (!beanalls.get(0).getLwhc().equals("")) {
                String data[] = beanalls.get(0).getLwhc().split(",");
                int money = 0;
                int num = Integer.valueOf(data[1]) + 1;
                String getLwhc = money + "," + num;
                Summary_Bean summary_bean = new Summary_Bean(beanalls.get(0).getZnqk(), beanalls.get(0).getXjhk(), beanalls.get(0).getZzhk(), beanalls.get(0).getYdhf(), beanalls.get(0).getLthf(), beanalls.get(0).getSgcc(), beanalls.get(0).getDzh(), beanalls.get(0).getHzd(), beanalls.get(0).getZhgm(), getLwhc, beanalls.get(0).getKtgs(), "", "", beanalls.get(0).getZhcqy(), beanalls.get(0).getZhgm(), beanalls.get(0).getHnyqy(), beanalls.get(0).getHnyjy());
                beanalls.clear();
                beanalls.add(summary_bean);
                Logger.e(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA");
                SpUtils.getSPUtil(getApplicationContext()).putString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", gson.toJson(beanalls));

            } else {
                Logger.e("aaaaaaaaaaaaaaaaaaaa");
                int num = 1;
                String getLwhc = "0" + "," + num;
                Summary_Bean summary_bean = new Summary_Bean(beanalls.get(0).getZnqk(), beanalls.get(0).getXjhk(), beanalls.get(0).getZzhk(), beanalls.get(0).getYdhf(), beanalls.get(0).getLthf(), beanalls.get(0).getSgcc(), beanalls.get(0).getDzh(), beanalls.get(0).getHzd(), beanalls.get(0).getZhgm(), getLwhc, beanalls.get(0).getKtgs(), "", "", beanalls.get(0).getZhcqy(), beanalls.get(0).getZhgm(), beanalls.get(0).getHnyqy(), beanalls.get(0).getHnyjy());
                beanalls.clear();
                beanalls.add(summary_bean);
                Logger.e(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA");
                SpUtils.getSPUtil(getApplicationContext()).putString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", gson.toJson(beanalls));

            }

        } else if (op_type.equals("mmjs")) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dealingLayout.setVisibility(View.GONE);
                    modificationSuccessLayout.setVisibility(View.VISIBLE);
                    modificationSuccessText.setText("解锁成功");
                }
            });

            PzGetUtils pzGetUtils = new PzGetUtils();
            pz_nums = pzGetUtils.pzutil(getApplication());
            Up_RundataUtils up_rundataUtils = new Up_RundataUtils();
            try {
                up_rundataUtils.packRequest("0200", "560000",
                        "000000000000000", "0", run_time, String.valueOf(num), f39);
            } catch (IOException e) {
                e.printStackTrace();
            }

            SpUtils.getSPUtil(getApplicationContext()).putString("all_make_type", "mmjs");
        } else if (op_type.equals("sgcz")) {
            Up_RundataUtils up_rundataUtils = new Up_RundataUtils();
            try {
                up_rundataUtils.packRequest("0420", "440000",
                        "000000000000000", "2", run_time, String.valueOf(num), f39);
            } catch (IOException e) {
                e.printStackTrace();
            }
            PzGetUtils pzGetUtils = new PzGetUtils();
            pz_nums = pzGetUtils.pzutil(getApplication());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    dealingLayout.setVisibility(View.GONE);
                    modificationSuccessLayout.setVisibility(View.VISIBLE);
                    modificationSuccessText.setText("冲正成功");
                }
            });


            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");// HH:mm:ss
            //获取当前时间
            Date date = new Date(System.currentTimeMillis());
            Gson gson = new Gson();
            //汇总查询
            String STAT_DATAALL = SpUtils.getSPUtil(getApplicationContext()).getString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", "");
            List<Summary_Bean> beanalls = gson.fromJson(STAT_DATAALL, new TypeToken<List<Summary_Bean>>() {
            }.getType());
            if (!beanalls.get(0).getSgcc().equals("")) {
                String data[] = beanalls.get(0).getSgcc().split(",");
                int money = 0;
                int num = Integer.valueOf(data[1]) + 1;
                String getSgcc = money + "," + num;
                Summary_Bean summary_bean = new Summary_Bean(beanalls.get(0).getZnqk(), beanalls.get(0).getXjhk(), beanalls.get(0).getZzhk(), beanalls.get(0).getYdhf(), beanalls.get(0).getLthf(), getSgcc, beanalls.get(0).getDzh(), beanalls.get(0).getHzd(), beanalls.get(0).getZhgm(), beanalls.get(0).getLwhc(), beanalls.get(0).getKtgs(), "", "", beanalls.get(0).getZhcqy(), beanalls.get(0).getZhcjy(), beanalls.get(0).getHnyqy(), beanalls.get(0).getHnyjy());
                beanalls.clear();
                beanalls.add(summary_bean);
                Logger.e(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA");
                SpUtils.getSPUtil(getApplicationContext()).putString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", gson.toJson(beanalls));

            } else {
                Logger.e("aaaaaaaaaaaaaaaaaaaa");
                int num = 1;
                String getSgcc = "0" + "," + num;
                Summary_Bean summary_bean = new Summary_Bean(beanalls.get(0).getZnqk(), beanalls.get(0).getXjhk(), beanalls.get(0).getZzhk(), beanalls.get(0).getYdhf(), beanalls.get(0).getLthf(), getSgcc, beanalls.get(0).getDzh(), beanalls.get(0).getHzd(), beanalls.get(0).getZhgm(), beanalls.get(0).getLwhc(), beanalls.get(0).getKtgs(), "", "", beanalls.get(0).getZhcqy(), beanalls.get(0).getZhcjy(), beanalls.get(0).getHnyqy(), beanalls.get(0).getHnyjy());
                beanalls.clear();
                beanalls.add(summary_bean);
                Logger.e(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA");
                SpUtils.getSPUtil(getApplicationContext()).putString(simpleDateFormat.format(date).replace("/", "") + "ALL_DATA", gson.toJson(beanalls));

            }

        }

    }
    public void clearImageMemoryCache(Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) { //只能在主线程执行
                Glide.get(context).clearMemory();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public void clearImageDiskCache(final Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.get(context).clearDiskCache();
// BusUtil.getBus().post(new GlideCacheClearSuccessEvent());
                    }
                }).start();
            } else {
                Glide.get(context).clearDiskCache();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private Bitmap getDiskBitmap(String pathString) {
        Bitmap bitmap = null;
        try {
            File file = new File(pathString);
            if (file.exists()) {
                bitmap = BitmapFactory.decodeFile(pathString);
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        return bitmap;
    }

//    public String readFile(String _path,String _fileName){
////        String res = "";
////        try {
////            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(_path+_fileName)));
////            String line = "";
////            while ((line = reader.readLine())!=null){
////                res+=line;
////            }
////        }catch (IOException e){
////            e.printStackTrace();
////        }
////        return res;
//        String path = _path+_fileName;
//        String content = ""; //文件内容字符串
//        //打开文件
//        File file = new File(path);
//        //如果path是传递过来的参数，可以做一个非目录的判断
//        if (file.isDirectory())
//        {
//            Log.d("TestFile", "The File doesn't not exist.");
//        }
//        else
//        {
//            try {
//                InputStream instream = new FileInputStream(file);
//                if (instream != null)
//                {
//                    InputStreamReader inputreader = new InputStreamReader(instream);
//                    BufferedReader buffreader = new BufferedReader(inputreader);
//                    String line;
//                    //分行读取
//                    while (( line = buffreader.readLine()) != null) {
//                        content += line + "\n";
//                    }
//                    instream.close();
//                }
//            }
//            catch (java.io.FileNotFoundException e)
//            {
//                Log.d("TestFile", "The File doesn't not exist.");
//            }
//            catch (IOException e)
//            {
//                Log.d("TestFile", e.getMessage());
//            }
//        }
//        return content;
//    }

    //初始化packView
    private void initPackView() {
        optionsPickerView = new OptionsPickerBuilder(this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                id_name = sf_strings.get(options1);
                bankName.setText(sf_strings.get(options1));
                id_num = "";
                if (id_name.equals("身份证")) {
                    id_num = "01";
                } else if (id_name.equals("军官证")) {
                    id_num = "02";
                } else if (id_name.equals("护照")) {
                    id_num = "03";
                } else if (id_name.equals("回乡证")) {
                    id_num = "04";
                } else if (id_name.equals("同胞证")) {
                    id_num = "05";
                } else if (id_name.equals("警官证")) {
                    id_num = "06";
                } else if (id_name.equals("士兵证")) {
                    id_num = "07";
                } else if (id_name.equals("港澳居民来往内地通行证")) {
                    id_num = "0G";
                } else if (id_name.equals("户口簿")) {
                    id_num = "0M";
                } else if (id_name.equals("对私其他证件")) {
                    id_num = "0N";
                } else if (id_name.equals("居民证")) {
                    id_num = "0O";
                } else if (id_name.equals("学生证")) {
                    id_num = "0S";
                } else if (id_name.equals("临时身份证")) {
                    id_num = "08";
                } else if (id_name.equals("其他证件")) {
                    id_num = "99";
                }
            }
        }).setOptionsSelectChangeListener(new OnOptionsSelectChangeListener() {
            @Override
            public void onOptionsSelectChanged(int options1, int options2, int options3) {

            }
        })
                .setSelectOptions(0)
                .build();
        optionsPickerView.setPicker(sf_strings);
    }

    private void setPickViewData() {
        sf_strings.add("身份证");
        sf_strings.add("军官证");
        sf_strings.add("护照");
        sf_strings.add("回乡证");
        sf_strings.add("同胞证");
        sf_strings.add("警官证");
        sf_strings.add("士兵证");
        sf_strings.add("港澳居民来往内地通行证");
        sf_strings.add("户口簿");
        sf_strings.add("对私其他证件");
        sf_strings.add("居民证");
        sf_strings.add("学生证");
        sf_strings.add("临时身份证");
        sf_strings.add("其他证件");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        bStop = true;
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            if (mDevice != null) {
                Log.w("ComShell", "mDevice is not null");
                if (shell != null) {
                    Log.w("ComShell", "shell is not null");
                    shell.Destroy();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
